<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\AdminUser;
use App\Models\Factory\AwAuditRecordFactory;
use App\Models\Orm\AwAuditRecord;
use App\Models\Orm\CooperativeCompany;
use App\Models\Orm\CooperativeCompanyAudit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


/**
 * 设置模块控制器
 * Class SettingController
 * @package App\Http\Controllers\Admin
 */
class SettingController extends Controller
{
    /**
     * 默认欢迎页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function welcome(Request $request)
    {
        // 当前操作人
        $user = auth('admin')->user();
        // 判断是否修改了默认密码
        $pw_reset = true;

        // 如果是三方用户并且未修改过密码
        if ($user->isOperator() && $user->pw_reset != AdminUser::PW_RESET_YES) {
            $pw_reset = false;

            // 如果是post提交
            if ($request->isMethod('post')) {
                // 验证参数
                $this->validate($request, [
                    // 密码(数字+字母,不能是纯数字或纯字母,6-10位)
                    'password' => ['required', 'regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/', 'min:6', 'max:20', 'confirmed'],
                    'password_confirmation' => 'required|min:6|max:20',
                ], [], [
                    'password' => '密码',
                    'password_confirmation' => '确认密码',
                ]);

                $password = $request->get('password');

                $user->password = bcrypt($password);
                $user->pw_reset = AdminUser::PW_RESET_YES;
                $user->save();

                return redirect('/admin/logout');
            }
        }

        return view('admin.setting.welcome', compact('pw_reset'));
    }

    /**
     * 合作方运营者管理
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function manager(Request $request)
    {
        $user = auth('admin')->user();

        if ($user->isOperator()) {

            // 如果是post提交
            if ($request->isMethod('post')) {
                // 验证参数
                $this->validate($request, [
                    // 密码(数字+字母,不能是纯数字或纯字母,6-10位)
                    'password' => ['required', 'regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/', 'min:6', 'max:20', 'confirmed'],
                    'password_confirmation' => 'required|min:6|max:20',
                ], [], [
                    'password' => '密码',
                    'password_confirmation' => '确认密码',
                ]);

                $password = $request->get('password');

                $user->password = bcrypt($password);
                $user->save();

                return redirect('/admin/logout');
            }
        }

        $user = $user->toArray();

        return view('admin.setting.manager', compact('user'));
    }

    /**
     * 展示公司信息
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        // 当前操作人
        $user = auth('admin')->user();

        // 三方运营展示自己公司信息
        if ($user->isOperator()) {

            // 正在审核的数据
            $audit_detail = [];

            // 查询认证申请记录表有没有该用户提交的未处理的记录
            $audit_record = AwAuditRecordFactory::getUserInitRecord($user->id, AwAuditRecord::ACTION_COMPANY);

            if ($audit_record) {
                // 找到对应提交审核申请的内容
                $audit_detail = CooperativeCompanyAudit::where('audit_record_id', $audit_record->id)->first();

                if (!$audit_detail) {
                    return back()->withErrors('错误,有正在审核的记录,但未找到相关内容');
                }
            }

            // 公司信息
            $company = CooperativeCompany::where('user_id', $user->id)->first();

            $data = [
                'company' => $company,
                'audit_detail' => $audit_detail,
                'audit_record' => $audit_record,
            ];

            return view('admin.setting.index', $data);
        }

        // 后台运营人员,展示所有公司列表
        $data = CooperativeCompany::orderBy('id', 'desc')->get();

        return view('admin.setting.companyList', compact('data'));
    }

    /**
     * 修改公司logo
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function alterLogo(Request $request)
    {
        $file = $request->file('company_logo');

        if (!$file) {
            return back()->withErrors('图片不能为空');
        }
        if (!$file->isValid()) {
            return back()->withErrors('图片格式有问题');
        }

        // 验证图片大小(最大2M)
        if ($file->getClientSize() > 20480000) {
            return back()->withErrors('图片最大2M');
        }

        // 验证图片格式(后期做到配置文件里)
        // TODO...

        // 查当前操作人公司记录
        $user = auth('admin')->user();

        $cooperative_company = CooperativeCompany::where('user_id', $user->id)->first();

        if (!$cooperative_company) {
            return back()->withErrors('未找到公司记录');
        }

        // 上传图片
        $company_logo = uploads($file, 'company_logo');

        // 修改公司记录的logo
        $cooperative_company->company_logo = $company_logo;

        if ($cooperative_company->save()) {

            return redirect('/admin/setting/index')->with(['success' => '修改成功']);
        }

        return back()->withErrors('修改失败');
    }

    /**
     * 修改公司审批logo
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function alterLogosp($file)
    {
//        $file = $request->file('company_logo');

        if (!$file) {
            return back()->withErrors('图片不能为空');
        }
        if (!$file->isValid()) {
            return back()->withErrors('图片格式有问题');
        }

        // 验证图片大小(最大2M)
        if ($file->getClientSize() > 20480000) {
            return back()->withErrors('图片最大2M');
        }



        // 上传图片
        $company_logo = uploads($file, 'company_logo');
        return $company_logo;

    }


    /**
     * 更改公司基本信息(简介、官网地址、咨询电话)
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function alterBasic(Request $request)
    {
        // 查当前操作人公司记录
        $user = auth('admin')->user();

        $cooperative_company = CooperativeCompany::where('user_id', $user->id)->first();

        if (!$cooperative_company) {
            return back()->withErrors('未找到公司记录');
        }

        // 修改公司记录
        $cooperative_company->company_desc = $request->get('company_desc');
        $cooperative_company->webiste_url = $request->get('webiste_url');
        $cooperative_company->advisory_telephone = $request->get('advisory_telephone');
        $cooperative_company->updated_at = date('Y-m-d H:i:s');

        if ($cooperative_company->save()) {
            return redirect('/admin/setting/index')->with(['success' => '修改成功']);
        }

        return back()->withErrors('修改失败');
    }

    /**
     * 公司认证申请提交
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function audit(Request $request)
    {
        // 当前操作人ID
        $user = auth('admin')->user();
        // 查询认证申请记录表有没有该用户提交的未处理的记录
        $audit_record = AwAuditRecordFactory::getUserInitRecord($user->id, AwAuditRecord::ACTION_COMPANY);
        if ($audit_record) {
            return back()->withErrors('您有正在审核的记录,请耐心等待审核结果');
        }

        // 查当前操作人公司信息记录
        $company = CooperativeCompany::where('user_id', $user->id)->first();
        if (!$company) {
            return back()->with(['error' => '未找到公司记录']);
        }

        // 表单提交
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'company_name' => 'required|max:50',
                'short_name' => 'required|max:10',
                'legal_person' => 'required|max:8',
                'legal_phone' => 'required|regex:/^1[34578][0-9]{9}$/',
            ]);

            DB::beginTransaction();

            $company_name = $request->input('company_name');
            $short_name = $request->input('short_name');
            $founding_time = $request->input('founding_time');
            $company_desc = $request->input('company_desc');
            $company_logo = $this->alterLogosp($request->file('company_logo'));
            $legal_person = $request->input('legal_person');
            $legal_phone = $request->input('legal_phone');
            $webiste_url = $request->input('webiste_url');
            $advisory_telephone = $request->input('advisory_telephone');

            // 审核申请记录表插入数据
            $insert_data = [
                'user_id' => $user->id,
                'action' => AwAuditRecord::ACTION_COMPANY,
                'order_id' => $company->id,
                'type' => AwAuditRecord::TYPE_EDIT,
                'status' => AwAuditRecord::STATUS_INIT,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            $audit_record_id = AwAuditRecord::insertGetId($insert_data);


            // 审核申请记录详情表插入数据
            $insert_data = [
                'user_id' => $user->id,
                'audit_record_id' => $audit_record_id,
                'company_name' => ($company->company_name != $company_name) ? $company_name : "",
                'short_name' => ($company->short_name != $short_name) ? $short_name : "",
                'founding_time' => ($company->founding_time != $founding_time) ? $founding_time : "",
//                'biz_license_no' => ($company->biz_license_no != $biz_license_no) ? $biz_license_no : "",
                'biz_license_no' => $company->biz_license_no,
                'company_desc' => ($company->company_desc != $company_desc) ? $company_desc : "",
                'company_logo' => ($company->company_logo != $company_logo) ?$company_logo : "",
                'legal_person' => ($company->legal_person != $legal_person) ? $legal_person : "",
                'legal_phone' => ($company->legal_phone != $legal_phone) ? $legal_phone : "",
                'webiste_url' => ($company->webiste_url != $webiste_url) ? $webiste_url : "",
                'advisory_telephone' => ($company->advisory_telephone != $advisory_telephone) ? $advisory_telephone : "",
                'created_at' => date('Y-m-d H:i:s'),
            ];

            CooperativeCompanyAudit::create($insert_data);

            DB::commit();

            return redirect('/admin/setting/index')->with(['success' => '递交成功,请您耐心等待后台审核']);
        }

        $data = [
            'company' => $company,
        ];

        return view('admin.setting.audit', $data);
    }

    /**
     * 插销审核申请
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function auditRepeal(Request $request)
    {
        $audit_id = $request->get('audit_id');

        if (!$audit_id) {
            return back()->withErrors('缺少参数');
        }

        // 查到该记录
        $audit_record = AwAuditRecord::find($audit_id);

        if (!$audit_record) {
            return back()->withErrors('未找到记录');
        }

        $user = auth('admin')->user();

        // 验证操作者
        if ($user->id != $audit_record->user_id) {
            return back()->withErrors('您无权修改该记录');
        }

        // 验证状态
        if ($audit_record->status != AwAuditRecord::STATUS_INIT) {
            return back()->withErrors('该记录状态不可更改');
        }

        // 执行状态修改
        $audit_record->status = AwAuditRecord::STATUS_REPEAL;
        $audit_record->updated_at = date('Y-m-d H:i:s');
        $audit_record->save();

        return redirect('/admin/setting/index')->with(['success' => '撤销成功']);
    }

    /**
     * 审核记录列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function auditList()
    {
        // 当前操作人
        $user = auth('admin')->user();

        // 查询条件
        $where = ['action' => AwAuditRecord::ACTION_COMPANY];

        if ($user->isOperator()) {
            $where['user_id'] = $user->id;
        }

        $data = AwAuditRecord::where($where)->orderby('id', SORT_DESC)->get();

        return view('admin.setting.auditList', compact('data'));
    }

    /**
     * 审批记录详情
     *
     * @param $id
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function auditShow($id)
    {
        $user = auth('admin')->user();

        // 审批记录信息
        $audit_record = AwAuditRecord::find($id);

        if (!$audit_record) {
            return back()->withErrors('未找到审核记录');
        }

        if ($audit_record->action != AwAuditRecord::ACTION_COMPANY) {
            return back()->withErrors('参数有误');
        }

        // 验证操作者
        if ($user->isOperator() && $user->id != $audit_record->user_id) {
            return back()->withErrors('您无权查看该记录');
        }

        // 公司审批详细信息
        $data = CooperativeCompanyAudit::where(['audit_record_id' => $audit_record->id])->first();

        return view('admin.setting.auditShow', compact('data'));
    }

}
